package com.LeetCode.doublePair;

import org.junit.Test;

import java.util.Arrays;

/**
 * 最接近的三数之和
 */
public class MostCloseTreeSum {

    public int threeSumClosest(int[] nums, int target) {
        int len = nums.length;
        Arrays.sort(nums);
        int ans = nums[0] + nums[1] + nums[2];
        for(int i = 0; i<len; i++){
            int l = i + 1, r = len - 1;
            while(l < r){
                int sum = nums[i] + nums[l] + nums[r];
                if(Math.abs(sum - target) < Math.abs(ans - target)){
                    ans = sum;
                }
                if(sum > target){
                    r--;
                }else if(sum < target){
                    l++;
                }else{
                    return sum;
                }
            }
        }
        return ans;
    }

    @Test
    public void test(){
        int[] arr = {-1,2,1,4};
        System.out.println(threeSumClosest(arr,1));
    }
}
